fetch 函数返回承诺而不是对象

时间:2021-01-24 08:26:48

标签: javascript promise

我在 getData 中有一个函数 functions.js,当我在另一个文件中调用时,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)

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

2 个答案:

答案 0 :(得分:1)

getData 是一个 async 函数并返回一个 Promise 并且 await 只允许在 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()

答案 1 :(得分:1)

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

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 函数都可以。 Promise 实际上永远不会消失async/await 只会隐藏它们。这是语法糖。这很重要:您不能从异步函数返回值,再多的语法糖也无法改变这一事实。

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

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

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

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