![](/img/trans.png)
[英]node.js promise: then() of promise nested inside a then() chain doesn't get resolved
[英]Node.JS Airtable - Await doesn't wait for promise to be resolved
我試圖從我的 node.js 應用程序中的 Airtable 獲取數據,但在我的承諾解決后我無法獲得我的結果。
這是我的代碼:
async function getData(code) {
return await airtableBase("Data")
.select({
filterByFormula: `{code} = "${code}"`,
})
.firstPage((err, records) => {
if (err) {
console.log(err);
return {};
}
console.log(records[0].fields);
return records[0].fields;
});
}
stuff.map(async (object) => {
embedData = getEmbedData(object);
data = await getData(embedData.code);
console.log(data);
})
這是我記錄的內容:
undefined
undefined
undefined
{
code: '1',
fullname: 'Test 1',
logo: '...'
}
{
code: '2',
fullname: 'Test 2',
logo: '...'
}
{
code: '3',
fullname: 'Test 3',
logo: '...'
}
你認為
airtableBase(...).select(...).firstPage((error, result) => {})
返回一個 Promise - 它沒有
很少有采用節點樣式回調的函數......即
function(error, result)
返回一個承諾
更改 getData 以返回 Promise
function getData(code) {
return new Promise((resolve, reject) => {
airtableBase("Data")
.select({
filterByFormula: `{code} = "${code}"`,
})
.firstPage((err, records) => {
if (err) {
console.log(err);
return reject({});
}
console.log(records[0].fields);
resolve(records[0].fields);
});
});
}
此外,與
stuff.map(async (object) => {
embedData = getEmbedData(object);
data = await getData(embedData.code);
console.log(data);
})
不能保證訂單是正確的,在這種情況下可能是正確的,但不能保證
上面寫的比較好
Promise.all(stuff.map((object) => {
embedData = getEmbedData(object);
return getData(embedData.code);
}))
.then(results => {
results.forEach(item => console.log(item));
})
或者如果該代碼在async
函數中
const results = await Promise.all(stuff.map((object) => {
embedData = getEmbedData(object);
return getData(embedData.code);
}))
results.forEach(item => console.log(item));
注意:絕對沒有拒絕測試,因為你的代碼沒有,但實際上,你應該 try/catch(如果使用 async/await)或 .catch 如果使用 .then
請注意,如果沒有給出回調函數,
.firstPage
實際上可能會返回一個 Promise,因此您的代碼可能會更簡單
function getData(code) {
return airtableBase("Data")
.select({
filterByFormula: `{code} = "${code}"`,
})
.firstPage()
.promise() /* this could be needed, again, depending on the library */
.then(records => {
return records[0].fields;
});
}
但是,由於您沒有指出有關您正在使用的 db 庫的任何信息,我無法確定上述內容是否有效
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.