gpt4 book ai didi

javascript - Node.js promise 和 for 循环

转载 作者:行者123 更新时间:2023-11-29 21:38:36 27 4
gpt4 key购买 nike

我设法做到了这一点,但我又卡住了。

我的 for 循环没有按我想要的方式工作。如果有三个 Angular 色,则只有最后一个被添加(三次)到我的数据透视表 MySQL 表中。 (因为它是异步的)

我怎样才能让它以“并行运行,但在添加他/她之后添加一个人的 Angular 色”的方式工作?我还想做其他类型的事情,比如下载图片,所以我正在寻找一种方法来实现“做这个,获取这个信息,然后做那个”。

我正在使用 bluebird 。

很抱歉,如果它太明显了,我无法理解该怎么做。

var entities = require("entities");
var request = require('request');
var cheerio = require('cheerio');

var person = require('./models').person;
var personRole = require('./models').personRole;
var personPersonRole = require('./models').personPersonRole;

// create promisified version of request()
function requestPromise(options) {
return new Promise(function (resolve, reject) {
request(options, function (err, resp, body) {
if (err) return reject(err);
resolve(body);
});
});
}

app.get('/fetch2', function (req, res) {
var promises = [];
var headers = {
'User-Agent': req.headers['user-agent'],
'Content-Type': 'application/json; charset=utf-8'
};
for (var i = 0; i < 10; i++) {
promises.push(requestPromise({url: "http://www.example.com/person/"+ i +"/personname.html", headers: headers}));
}
Promise.all(promises).then(function (data) {
// iterate through all the data here
data.forEach(function (item, i) {
var $ = cheerio.load(item);
var name = $("#container span[itemprop='name']").text();
if (!name) {
console.log("null name returned, do nothing");
} else {
// name exists
person.where('id', i).fetch({require: true}).then(function (p) {
console.log("exists");
}).catch(function () {
console.log(i + " does not exist");
new person({id: i, name: name}).save(null, {method: 'insert'}).then(function (returnval) {

var numberOfRoles = $('span[itemprop="jobtitle"]').length;
for (var b = 0; b < numberOfRoles; b++) {
var personType = $('span[itemprop="jobtitle"]').eq(b).text();
var personType = entities.decodeHTML(personType);
personRole.where('person_role', personType).fetch().then(function (pResult) {
new personPersonRole({
person_id: i,
personrole_id: pResult.id
}).save();
}).catch(function () {
console.log("this role doesn't exist in the database, now it will be added. then this role's id and" +
"person id will be added to the pivot table");
new personRole({
person_type: personType
}).save().then(function (data5) {
new personPersonRole({
person_id: i,
personrole_id: data5.id
}).save();
});
});
}
});
});
}
}, function (err) {
// error occurred here
console.log(err);
});
});
});

最佳答案

您需要使用闭包 来保存异步函数的i 上下文。不过,我相信有一种更像 Promises 风格的方法可以做到这一点。

例子:

(function() {
var personId = i;
person.where('id', personId).fetch({require: true}).then(function (p) {
console.log(personId); // This will give the 'saved' value, instead of whatever i is when the callback finishes.
....
});
})();

关于javascript - Node.js promise 和 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34011729/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com