我正在尝试编写一个JS代码,如果数据库中已存在给定的数字,它将取消"btn_submit"按钮.onclick事件.我使用AJAX查询给定数字的数据库,并确定是否应该将数据发送到将上传问题的.php站点.为了确定这一点,我需要numOfRows变量的值,但因为我在AJAX中设置它将保持为0. validation()函数将在我的AJAX查询完成之前完成,这会导致问题始终表明给定的数字不是存在于DB中(numOfRows将始终保持为0).在我将validation()函数的结束行中的numOfRows与0进行比较之前,如何等待AJAX查询完成?如果数字中已存在该数字,我需要将false返回到此行:
document.getElementById("btn_submit").onclick = validation;
谢谢!
var textAreaList;
var numOfRows = 0;
var finished = false;
document.getElementById("btn_submit").onclick = validation;
textAreaList = document.getElementsByClassName("text_input");
function validation() {
loadNumRows();
try {
document.getElementById('failure').hidden = true;
}
catch(e) {
console.log(e.message);
}
textAreaList = document.getElementsByClassName("text_input");
var failValidation = false;
for (var i = 0; i < textAreaList.length; i++) {
console.log(textAreaList[i]);
if (textAreaList[i].value == "") {
textAreaList[i].style.border = "2px solid #ff0000";
failValidation = true;
} else {
textAreaList[i].style.border = "2px solid #286C2B";
}
}
return !(failValidation || …Run Code Online (Sandbox Code Playgroud) UPDATE
我已经阅读了十几篇关于这个主题的文章,其中没有一篇论述这个基本问题.我将在本文末尾开始列出资源部分.
原始邮政
我对async函数的理解是它返回一个承诺.
MDN文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
在我的程序中,我可以写一些像:
function testPromise() {
return new Promise((resolve, reject) => {
// DO WORK
reject() // IF WORK FAILS
resolve() // IF WORK IS SUCCESSFUL
})
}
async function mainFunction() {
let variable
try {
variable = await testPromise()
} catch(e) {
throw e
}
return variable
}
Run Code Online (Sandbox Code Playgroud)
我也可以将testPromise编写为异步函数,并await在同一个上下文中编写.
async function testAsyncFunction() {
//DO WORK AND THROW ERROR IF THEY OCCUR
}
async function mainFunction() {
let variable
try …Run Code Online (Sandbox Code Playgroud) 我正在调用 React Native API。
理论上它应该工作 -
import API from "../../utils/API";
componentDidMount() {
let merchantId = this.props.merchant.id;
let api = new API(this.props.gatheredTokens);
let self = this;
api.setRetry(10);
api
.get("merchantMessages", { repl_str: merchantId })
.then(response => this.merchantMessageConfiguration(response.data))
.catch(function (error) {
console.log(error);
})
.finally(function () {
self.state.list.push(
<Card
merchant={self.props.merchant}
key={self.props.merchant.id}
bubblemsg={self.state.bubblemsg}
/>
);
})
.finally(function () {
self.merchantNoticeLoading(self);
});
}
Run Code Online (Sandbox Code Playgroud)
但是我收到以下错误:
是什么导致了这个错误?该代码看起来有效。
这是得到的是:
get(API, params = this.defaultParams) {
this.call = "GET";
let constructedURL = this.constructURL(API, params);
axiosRetry(axios, { retries: this.retry });
return axios.get(constructedURL, …Run Code Online (Sandbox Code Playgroud) 我是这样的承诺,
function getMode(){
var deferred = Promise.defer();
checkIf('A')
.then(function(bool){
if(bool){
deferred.resolve('A');
}else{
return checkIf('B');
}
}).then(function(bool){
if(bool){
deferred.resolve('B');
}else{
return checkIf('C');
}
}).then(function(bool){
if(bool){
deferred.resolve('C');
}else{
deferred.reject();
}
});
return deferred.promise;
}
Run Code Online (Sandbox Code Playgroud)
checkIf返回一个promise,是的checkIf ,无法修改.
我如何在第一场比赛中脱颖而出?(除了明确抛出错误之外的任何其他方式?)
我担心我使用JQuery兼容的promises看到Parse的引用,因为我已经读过jQuery promises 允许消费者改变promise的状态.是否可以使用Parse JavaScript SDK 使用已知为Promises/A +的另一个promise实现(例如ECMAScript 6实现,或Bluebird)?
通常我会认为这是不可能的,但是在Parse JavaScript SDK的v1.4.2中,Parse.Promise的实现将属性"_isPromisesAPlusCompliant"定义为false,然后在库中的各种函数中进行检查.
NB此问题最初是在Parse Developers小组中提出的,但未收到任何回复.
我试图save()从子实例调用super方法.
// ImageKeeper.js
'use strict';
module.exports = class ImageKeeper extends FileKeeper {
constructor(keeperPath, options) {
super(`/${keeperPath}`, options)
this.keeperPath = keeperPath;
}
save(filePath) {
return new Promise((resolve, reject) => {
this
.resolvePath(filePath)
.then(function(fileData) {
var filePath = fileData[0],
mime = fileData[1];
super.save(filePath, mime); // <-- GETTING ERROR HERE
})
.catch(function(err) {
reject(err)
})
})
}
}
// FileKeeper.js
'use strict';
module.exports = class FileKeeper {
constructor(keeperPath, options) {
this.storagePath = path.resolve(`${env.paths.storage}${keeperPath}`);
this.options = options;
}
save(filePath, mime) {
return …Run Code Online (Sandbox Code Playgroud) 在我从请求返回之前,我需要等待完成的一些异步方法.我正在使用Promises,但我一直收到错误:
Each then() should return a value or throw // promise/always-return
Run Code Online (Sandbox Code Playgroud)
这为什么开心呢?这是我的代码:
router.get('/account', function(req, res) {
var id = req.user.uid
var myProfile = {}
var profilePromise = new Promise(function(resolve, reject) {
var userRef = firebase.db.collection('users').doc(id)
userRef.get()
.then(doc => { // Error occurs on this line
if (doc.exists) {
var profile = doc.data()
profile.id = doc.id
myProfile = profile
resolve()
} else {
reject(Error("Profile doesn't exist"))
}
})
.catch(error => {
reject(error)
})
})
// More promises further on, which I …Run Code Online (Sandbox Code Playgroud) 如何在以后检索承诺的结果?在测试中,我在发送进一步请求之前检索电子邮件:
const email = await get_email();
assert.equal(email.subject, 'foobar');
await send_request1();
await send_request2();
Run Code Online (Sandbox Code Playgroud)
如何在慢速邮件检索过程中发送请求?
起初,我考虑过稍后等待电子邮件:
// This code is wrong - do not copy!
const email_promise = get_email();
await send_request1();
await send_request2();
const email = await email_promise;
assert.equal(email.subject, 'foobar');
Run Code Online (Sandbox Code Playgroud)
如果get_email()成功,这可以工作,但如果get_email()在相应的之前失败则失败await,并且完全合理UnhandledPromiseRejectionWarning.
当然,我可以使用Promise.all,像这样:
await Promise.all([
async () => {
const email = await get_email();
assert.equal(email.subject, 'foobar');
},
async () => {
await send_request1();
await send_request2();
},
]);
Run Code Online (Sandbox Code Playgroud)
然而,它使代码更难阅读(它看起来更像是基于回调的编程),尤其是在以后的请求实际上依赖于电子邮件,或者有一些嵌套回事.是否可以在以后存储承诺的结果/例外await?
如果需要,这里有一个带有模拟 …
我有一个服务正在向后端发出AJAX请求
服务:
function GetCompaniesService(options)
{
this.url = '/company';
this.Companies = undefined;
this.CompaniesPromise = $http.get(this.url);
}
Run Code Online (Sandbox Code Playgroud)
控制器:
var CompaniesOb = new GetCompanies();
CompaniesOb.CompaniesPromise.then(function(data){
$scope.Companies = data;
});
Run Code Online (Sandbox Code Playgroud)
我希望我的服务能够处理".then"函数,而不必在我的控制器中处理它,并且我希望能够让我的控制器在服务中的承诺解决之后对服务中的数据进行操作.
基本上,我希望能够像这样访问数据:
var CompaniesOb = new GetCompanies();
$scope.Companies = CompaniesOb.Companies;
Run Code Online (Sandbox Code Playgroud)
随着承诺的解决在服务本身内部处理.
这可能吗?或者是我能够访问该承诺的唯一方法是解决方案来自服务外部吗?
我有以下小提琴:http: //jsfiddle.net/thelgevold/3uv9nnjm/6/
angular.module('hello',[]).controller('helloController',function($q){
console.clear();
function someService(){
var deferred = $q.defer();
deferred.reject({e:'error'});
return deferred.promise;
}
function callService(){
return someService().then(function(obj){
console.log('first then');
}).
catch(function(e){
console.log('error1');
var deferred = $q.defer();
deferred.reject({e:'error'});
return deferred.promise;
});
}
callService().catch(function(e){
console.log('error2');
}).then(function(e){
console.log('second then');
});
});
Run Code Online (Sandbox Code Playgroud)
它基本上只是一个快速的$ q承诺POC.我的问题是:为什么在承诺被拒绝时会调用last then子句?输出如下:
ERROR1
误差2
第二个
我理解为什么会打印error1/error2,但我认为第二个字符串不应该打印,因为承诺被拒绝了.我认为它会省略"第二个然后",出于同样的原因,"第一个然后"被省略.有什么想法吗?
javascript ×9
promise ×5
es6-promise ×3
ajax ×2
angularjs ×2
async-await ×2
node.js ×2
bluebird ×1
ecmascript-6 ×1
inheritance ×1
jquery ×1
php ×1
react-native ×1
reactjs ×1
scope ×1
super ×1