gpt4 book ai didi

node.js - 如何链接 promise 和多个异步请求?

转载 作者:太空宇宙 更新时间:2023-11-04 00:03:55 26 4
gpt4 key购买 nike

我从 api 请求数据,然后将其存储到数据库:

数据库

MongoClient.connect(url, { useNewUrlParser: true })
.then((db)=>{
let dbo = db.db("scraper");
// This will be the api-response:
dbo.collection("sold").insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
db.close();
})
.catch(err => {
console.log(err)
});

API

fetch(link, {headers: {"Content-Type": "application/json; charset=utf-8"}})
.then(res => res.json()) // parse response as JSON (can be res.text() for plain response)
.then(response => {
console.log(util.inspect(response, {showHidden: false, depth: null, colors: true}));
// This is where I'll be storing the data
})
.catch(err => {
console.log(err)
});

我可以将获取响应嵌套在 MongoClient 中,但我更愿意启动两个请求,然后在它们都完成后启动一系列 promise 。这可能吗?

最佳答案

如果你想同时启动 Promise,你应该尝试使用 Promise.All。

这是一个例子

var promise1 = Promise.resolve(3);
var promise2 = 42;
var promise3 = new Promise(function(resolve, reject) {
setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then(function(values) {
console.log(values);
});
// expected output: Array [3, 42, "foo"]

关于node.js - 如何链接 promise 和多个异步请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53241403/

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