一個簡單的腳本,我想要實作的是在 append 方法中推送新專案,并使用異步函式
我試圖了解 then 和 catch 是如何作業的,而不是在不了解它們內部如何作業的情況下使用它們(使用 axios 或其他東西)
推送必須在 3 秒后執行
我試圖在里面使用 resolve 方法,setTimeout但我收到一個錯誤,因為resolve沒有被識別,我正在回傳一個 Promise 因為我不能等待一個setTimeout
<script>
async function test(terms) {
let termss = await append(terms);
return [termss[termss.length - 2], termss[termss.length - 1]]
}
async function append(arr) {
var arrr = arr;
const waitFor = () => new Promise(resolve => {
setTimeout((resolve) => {
arrr.push("Taoufiq")
arrr.push("understands");
}, 3000)
});
await waitFor();
return arrr;
}
test([1, 2, 3, 9]).then((result) => {
console.log(result)
})
</script>
AYY 幫助了解這是如何作業的?
我的預期結果是回傳一個陣列 ["Taoufiq", "understands"]
uj5u.com熱心網友回復:
您應該能夠使用以下代碼執行您想要的操作:
async function test(terms) {
let termss = await append(terms);
return [termss[termss.length - 2], termss[termss.length - 1]]
}
async function append(arr) {
return new Promise(resolve => {
setTimeout(() => {
arr.push("Taoufiq")
arr.push("understands");
resolve(arr)
}, 3000)
});
}
test([1, 2, 3, 9]).then((result) => {
console.log(result)
})
所以,你必須回傳新無極里面append的功能和使用resolve方法無極構造給予你內心的setTimemout。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/386091.html
