簡體   English   中英

NodeJS-意外的標識符正在等待

[英]NodeJS - Unexpected identifier await

我使用NodeJS並嘗試通過異步/等待來包裝我的代碼,但是每次都會收到“ SyntaxError:意外的標識符”錯誤。 這是我的代碼:

async function showOff(phone) {
    return new Promise((resolve, reject) => {
        var message = 'Hey friend, I have a new ' + phone.color + ' ' + phone.brand + ' phone';
        resolve(message);
    });
};

let message = await showOff({ color: "black", brand: "Sony" });

有什么問題

await只能在async函數內使用。

 function showOff(phone) { return new Promise((resolve, reject) => { var message = 'Hey friend, I have a new ' + phone.color + ' ' + phone.brand + ' phone'; resolve(message); }); }; async function phone() { let message = await showOff({ color: "black", brand: "Sony" }); console.log(message); } phone(); 

async表示哪個函數正在等待響應,而不是執行異步操作的函數。

從文檔https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await

等待操作符用於等待Promise。 它只能在異步函數中使用。

因此,您只需將所有代碼包裝在匿名aync函數中

(async () => {
    async function showOff(phone) {
        return new Promise((resolve, reject) => {
            var message = 'Hey friend, I have a new ' + phone.color + ' ' + phone.brand + ' phone';
            resolve(message);
        });
    };

    let message = await showOff({ color: "black", brand: "Sony" });

    console.log(message);
})();

在某些情況下,這可能是一個簡單的解決方案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM