How to promisify correctly JSON.parse method with bluebird

后端 未结 3 1982
被撕碎了的回忆
被撕碎了的回忆 2021-02-14 12:24

I\'m trying to promisify JSON.parse method but unfortunately without any luck. This is my attempt:

Promise.promisify(JSON.parse, JSON)(data).then((r         


        
3条回答
  •  醉梦人生
    2021-02-14 12:52

    Promise.promisify is thought for asynchronous functions that take a callback function. JSON.parse is no such function, so you cannot use promisify here.

    If you want to create a promise-returning function from a function that might throw synchronously, Promise.method is the way to go:

    var parseAsync = Promise.method(JSON.parse);
    …
    
    parseAsync(data).then(…);
    

    Alternatively, you will just want to use Promise.resolve to start your chain:

    Promise.resolve(data).then(JSON.parse).then(…);
    

提交回复
热议问题