我正在参加一个名为 promise-it-wont-hurt 的关于异步编程的 js/node 研讨会。我有以下练习:
parsePromised
的函数,该函数创建一个承诺,执行JSON.parse
在 try
/catch
块中,并根据是否抛出错误来实现或拒绝承诺。 注意:您的函数应该同步返回承诺!我的回答:
function parsePromised(json) {
return new Promise(function(resolve, reject){
resolve( JSON.parse(json) ),
reject(throwError)
});
}
parsePromised(process.argv[2]).then(console.log);
堆栈跟踪是:
(node:3499) UnhandledPromiseRejectionWarning: SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at /home/optionhomes11/nodeprojects/promise-shop/test.js:184:21
at new Promise (<anonymous>)
at parsePromised (/home/optionhomes11/nodeprojects/promise-shop/test.js:183:10)
练习结果给出:
Your solution to Throw an error didn't pass. Try again!
知道如何让它工作吗?
更改为 answer 中的代码后,堆栈跟踪:
(node:5533) UnhandledPromiseRejectionWarning: SyntaxError:
Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at /home/optionhomes11/nodeprojects/promise-shop/test.js:186:34
at new Promise (<anonymous>)
at parsePromised (/home/optionhomes11/nodeprojects/promise-shop/test.js:184:10)
at Object.<anonymous> (/home/optionhomes11/nodeprojects/promise-shop/test.js:196:1)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain]
(internal/modules/run_main.js:60:12)
(node:5533) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
答案 0 :(得分:1)
根据你提到的说明,我认为你想这样做
function parsePromised(json) {
return new Promise(function(resolve, reject){
try {
const parsedJson = JSON.parse(json);
resolve(parsedJson);
} catch(error) {
// we reach in this block if we encounter error while parsing some invalid given json
reject(error);
//or reject(error.message);
}
});
}
现在你这样称呼它
parsePromised(process.argv[2])
.then(console.log)
.catch(function(err) {
console.log("some error occured while parsing the json");
console.log("error is:", err.message);
});
基本上,当您尝试获得承诺结果时,您在承诺中拒绝的任何内容都会捕获高阶函数。
答案 1 :(得分:0)
你快到了,你只是错过了最后一步:
<块引用>构建一系列类似于上面显示的步骤捕获任何抛出的错误并将它们记录到控制台。
如果结果不是错误,您只是在记录结果。改成
parsePromised(process.argv[2]).catch(console.log);
// ^^^^^
另请注意,您不需要显式调用 reject
- the Promise
constructor already handles exceptions thrown from the executor。所以你需要做的就是
function parsePromised(json) {
return new Promise(function(resolve, reject){
resolve( JSON.parse(json) )
});
}
如果你想自己发现错误,你宁愿写
function parsePromised(json) {
try {
return Promise.resolve( JSON.parse(json) );
} catch(thrownError) {
return Promise.reject(thrownError);
}
}