【问题标题】:fetch function returns promise instead of object [duplicate]fetch函数返回promise而不是对象[重复]
【发布时间】:2021-04-28 07:07:56
【问题描述】:

我在functions.js 中有一个函数getData,当我在另一个文件中调用scripts.js 时,它返回promise 而不是对象。

//------ functions.js ------

export async function getData(arg1,arg2,arg3) {

...

let result = await fetch(proxyUrl + targetUrl, requestOptions)
    .then(response => response.json())
    .catch(error => console.log('error', error));

return result
    }

当我这样调用时,我得到了一个 Promise:

//------ scripts.js ------

import {getData} from './functions';

let result = getData(arg1,arg2,arg3)
console.log(result)

但即使我这样调用,我也会收到错误:

//------ scripts.js ------

import {getData} from './functions';

let result = awiat getData(arg1,arg2,arg3)
console.log(result)

“未捕获的语法错误:意外的保留字”

【问题讨论】:

  • 这里有错字awiat --> let result = awiat getData(arg1,arg2,arg3)
  • 对于第一个 sn-p,预期结果不是对象而是承诺。其次,我希望awiat 只是一个错字?如果你有await,这只能在异步函数中使用

标签: javascript promise


【解决方案1】:

getData 是一个 async 函数并返回一个 Promiseawait 只允许在 async 函数内。

export async function getData(arg1,arg2,arg3) {
  try {
    const response = await fetch(proxyUrl + targetUrl, requestOptions)
    return await response.json()
  } catch(err) {
    console.log(err)
    throw err
  }
}
import { getData } from './functions';

getData(arg1,arg2,arg3).then(result => {
  console.log(result)
})

或者这样

import { getData } from './functions';

const print = async () => {
  const result = await getData(arg1,arg2,arg3)
  console.log(result)
}

print()

【讨论】:

  • 其实我不想打印对象,我想把它保存为对象。在这里,我想将 getData 函数的输出保存在结果中。所以我以后可以使用它。
【解决方案2】:

不要使用 .then().catch() 显式基于 promise 的代码,而是在 async 函数中使用 try/catch 块和实际的 return 语句:

export async function getData(proxyUrl, targetUrl, requestOptions) {
    try {
        let response = await fetch(proxyUrl + targetUrl, requestOptions);
        return response.json();
    } catch (error) {
        console.log('error', error);
    }
}

当然,这个函数仍然返回一个Promise。每个async 函数都可以。承诺实际上永远不会消失async/await 只会隐藏它们。它是语法糖。这很重要:您不能从异步函数返回值,再多的语法糖也无法改变这一事实。

所以当你调用它时,要么await它在另一个async函数中

async function main() { 
    var data = await getData(...);
}

或在常规函数中使用 Promise 语义:

function main() { 
    getData(...).then(data => ...);
}

【讨论】:

  • 其实我不想打印对象,我想把它保存为对象。在这里,我想将 getData 函数的输出保存在结果中。所以我以后可以使用它。
  • @DSaad 不确定您指的是什么。我的答案中的代码不会“打印”该对象。你还没有真正阅读我写的内容。
猜你喜欢
  • 2018-11-03
  • 2017-09-10
  • 1970-01-01
  • 1970-01-01
  • 2017-01-19
  • 2019-12-29
  • 2020-01-21
  • 2022-11-14
相关资源
最近更新 更多