簡體   English   中英

JS Promise 解析 object

[英]JS Promise resolve object

以下方法驗證 JWT 並返回 id 和過期時間。

verify(token, secret = "jwtSecret") {
    console.log("verify jwt: ", secret);
    return new Promise(function (resolve, reject) {
        jwt.verify(
            token,
            _.get(strapi.plugins, ['users-permissions', 'config', secret]),
            {},
            function (err, tokenPayload = {}) {
                if (err) {
                    return reject(new Error('Invalid token.'));
                }
                console.log(tokenPayload);
                resolve(tokenPayload);
            }
        );
    });
},

當我調用驗證時,我期望返回以下 object

Promise { { id: 77, iat: 1593603153, exp: 1596195153 } }

但我無法訪問 object 的 ID。

當我在執行console.log("user id: ", payload.id)時,payload.id 在控制台中顯示為未定義

async refreshToken(ctx) {
    const { token } = ctx.request.body;
    const payload = strapi.plugins['users-permissions'].services.jwt.verify(token, "jwtRefreshSec");
    console.log("auth: ", payload); // this log ->  Promise { { id: 77, iat: 1593603153, exp: 1596195153 } } 
    console.log("user id: ", payload.id); // this log -> undefined
    return data;

},

正如Andreas所建議的,最好回顧一下 Promise 是如何工作的。

來自 MDN:

Promise object 表示異步操作的最終完成(或失敗)及其結果值。

Promise 是在創建 promise 時不一定知道的值的代理。

在您的第一種情況下( console.log("auth: ", payload); ), console.log function 知道它應該在收到 promise 的值后打印它。

在第二種情況下,( console.log("user id: ", payload.id); ),當您嘗試訪問結果的 id 屬性時,promise 尚未解決。

有 2 種方法可以解決此問題。

方法一:使用then

refreshToken(ctx) {
    const { token } = ctx.request.body;
    const payload = strapi.plugins['users-permissions'].services.jwt.verify(token, "jwtRefreshSec")
        .then(payload => {
            console.log("auth: ", payload); // this log ->  { id: 77, iat: 1593603153, exp: 1596195153 }
            console.log("user id: ", payload.id); // this log -> 77
            return data;
        });
   
},

方法二:ES2017 Aysnc/Await

async refreshToken(ctx) {
    const { token } = ctx.request.body;
    const payload = await strapi.plugins['users-permissions'].services.jwt.verify(token, "jwtRefreshSec");
    // Will wait for promise to resolve before continuing with await above
    console.log("auth: ", payload); // this log ->  { id: 77, iat: 1593603153, exp: 1596195153 }
    console.log("user id: ", payload.id); // this log -> 77
    return data;

},

暫無
暫無

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

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