【发布时间】:2020-01-21 13:23:59
【问题描述】:
我有以下情况:
我有一些在本地服务器上运行的代码(只需要支持 Chrome)。此代码当前运行异步,因为它来自教程。但是,对于我的用例来说,让代码同步运行会容易得多。
function creosonConnect() {
// JSON request
var reqObj = {
"command": "connection",
"function": "connect"
};
// perform the request
creosonRequest(reqObj)
.then(function(respObj) {
console.log('got this back: '+JSON.stringify(respObj));
console.log('SESSIONID ===> '+respObj.sessionId);
creosonSessionId = respObj.sessionId;
});
}
function creosonRequest (dataObj) {
return new Promise(function(resolve, reject) {
creosonServerSettingsObj.data = JSON.stringify(dataObj);
$.ajax(
creosonServerSettingsObj
)
.success(function (data) {
console.log('got to the success : '+JSON.stringify(data))
console.log('got this data type back: '+typeof data);
if (data.status.error) {
if (data.status.hasOwnProperty('message')) {
reject(data.status.message);
} else {
console.log(JSON.stringify(data));
reject('creoson Operation failed! - check console for details');
}
} else {
resolve(data);
}
})
.error( function (e) {
console.log('got an error : '+JSON.stringify(e));
reject('creoson Operation failed! - check console for details');
});
})
}
我的问题是我在一般的服务器/Web 开发方面的经验为零。如果我尝试链接几个依赖于第一个(creosonConnect)完成的功能,它会在我周围崩溃。 理想情况下,我想做这样的事情:
function main(){
creosonConnect();
creoOpenModel();
...
}
function creoOpenModel (partName) {
// JSON request
var reqObj = {
"sessionId": creosonSessionId,
"command": "file",
"function": "open",
"data": {
"file": null,
"display": true,
"activate": true
}
};
// get the input value & set to the reqObj
var fileName = partName
reqObj.data.file = fileName;
// perform the request
creosonRequest(reqObj)
.then(function(respObj) {
console.log('got this back: ' + JSON.stringify(respObj));
});
}
非常感谢任何帮助如何将其转换为同步代码。还有一些解释 creosonRequest 函数中到底发生了什么会很棒。
我知道这有很多问题,但我真的很茫然。提前非常感谢您!
【问题讨论】:
-
可以使用异步等待函数
-
“将 promise/ajax 转换为同步请求”——你不能这样做。
-
@Max 我已经偶然发现了这个概念,但不幸的是我不确定如何在我的特定情况下实现它。你能指出我正确的方向吗?
-
@frage12358 — 这就是 promise 对象的
then方法的用途。 -
@Quentin 有很多关于它的文档。我最近读过的一篇文章是css-tricks.com/understanding-async-await
标签: javascript ajax asynchronous promise synchronous