How to promisify correctly JSON.parse method with bluebird

后端 未结 3 1980
被撕碎了的回忆
被撕碎了的回忆 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:44

    Late to the party, but I can totally understand why you might want a promisified JSON parse method which never throws exceptions. If for nothing else, then to remove boilerplate try/catch-handling from your code. Also, I see no reason why synchronous behavior shouldn't be wrapped in promises. So here:

    function promisedParseJSON(json) {
        return new Promise((resolve, reject) => {
            try {
                resolve(JSON.parse(json))
            } catch (e) {
                reject(e)
            }
        })
    }
    

    Usage, e.g:

    fetch('/my-json-doc-as-string')
      .then(promisedParseJSON)
      .then(carryOn)
      .catch(dealWithIt)
    

提交回复
热议问题