我有一个foo发出Ajax请求的函数.我怎样才能从中回复foo?
我尝试从success回调中返回值,并将响应分配给函数内部的局部变量并返回该变量,但这些方法都没有实际返回响应.
function foo() {
var result;
$.ajax({
url: '...',
success: function(response) {
result = response;
// return response; // <- I tried that one as well
}
});
return result;
}
var result = foo(); // It always ends up being `undefined`.
Run Code Online (Sandbox Code Playgroud) 设置和环境:应用程序使用 create-react-app 创建,包含在 App.js 中,并在命令行使用 npm start 运行。
强制性源代码:
import React from 'react';
import ReactDOM from 'react-dom';
import logo from './logo.svg';
import './App.css';
async function getRemoteData() {
var result = [];
const response = await fetch('some.site.that.returns.json'); // not the actual URL although you get the idea
const json = await response.json();
for (const entry of json.entry) {
result.push(json.fullUrl);
console.log(json.fullUrl);
}
console.log("String representation");
console.log(result.toString());
// Following commented string used to test ReactJS functionality
// return "";
return result.toString();
}
// minimalist …Run Code Online (Sandbox Code Playgroud)