【发布时间】:2019-06-14 14:43:50
【问题描述】:
我正在学习node js中的promise。我写了一段代码如下。
var request = require("request");
var userDetails;
function getData(url) {
// Setting URL and headers for request
var options = {
url: url,
headers: {
'User-Agent': 'request'
}
};
// Return new promise
return new Promise(function (resolve, reject) {
// Do async job
request.get(options, function (err, resp, body) {
if (err) {
reject(err);
} else {
resolve(body);
}
})
})
}
var errHandler = function (err) {
console.log(err);
}
function main() {
var userProfileURL = "https://api.githshub.com/users/narenaryan";
var dataPromise = getData(userProfileURL);
// Get user details after that get followers from URL
var whichPromise = dataPromise.then(JSON.parse)
.then(function (result) {
userDetails = result;
// Do one more async operation here
console.log("then1")
var anotherPromise = getData(userDetails.followers_url).then(JSON.parse);
return anotherPromise;
})
.then(function (data) {
return data
});
console.log(whichPromise)
whichPromise.then(function (result) {
console.log("result is" + result)
}).catch(function (error) {
console.log("Catch" + error)
});
}
main();
现在这工作得很好。我有这方面的疑问。
1. JSON.Parse 如何在不获取 json 字符串的情况下解析数据。
var whichPromise = dataPromise.then(JSON.parse)
2.如果我在下面的行中输入了错误的 url
var userProfileURL = "https://api.githshub.com/users/narenaryan";
然后阻止将不起作用,因为 DNS 将无法解析并且应该得到一个错误,这意味着
var anotherPromise = getData(userDetails.followers_url).then(JSON.parse);
return anotherPromise;
不会返回任何值,whichPromise 不会有任何引用。
但是如果调用下面的代码
whichPromise.then(function (result) {
console.log("result is" + result)
}).catch(function (error) {
console.log("Catch" + error)
});
这里 whichPromise 能够调用 catch 块。有人能解释一下为什么吗?
【问题讨论】:
-
你只是将
JSON.parse函数作为参数传递,见this,它类似于写.then(x => JSON.parse(x)),每个promise都应该在then链的末尾包含一个catch块 -
如果你输入了错误的
url,就会出现错误if (err) {reject(err); },所以whichPromise可以调用catch块。 IMO 拒绝像throw error这样的工作,但在异步回调中,您必须使用拒绝而不是throw error
标签: node.js promise es6-promise node-modules